<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <UploadExcel :on-success="upload" />
      </el-card>
    </div>
  </div>
</template>

<script>
import { importEmployee } from '@/api/employee'
export default {
  methods: {
    async upload(val) {
      const { results } = val
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const newData = results.map(item => {
        return this.toggle(item, userRelations)
      })
      console.log(newData)
      // 发请求
      await importEmployee(newData)
      // 提示
      this.$message.success('导入成功')
      // 回退
      this.$router.back()
    },
    // 中文装英文
    toggle(item, userRelations) {
      const res = {}
      for (const key in item) {
        // 获取英文名
        const enkey = userRelations[key]
        // 获取值
        let value = item[key]
        // 时间处理
        if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          value = new Date(this.formatDate(value, '-'))
        }
        // 添加到对象中
        res[enkey] = value
      }
      return res
    },
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  padding-bottom: 100px;
}
</style>
